import WxRequest from 'mina-request'
import { clearStorage, getStorage } from '../utils/storage'
import { env } from './env'

const instance = new WxRequest({
  baseURL: env.baseURL,
  timeout: 15000,
  isLoading: false
})

// 添加请求拦截器
instance.interceptors.request = (config) => {
  const token = getStorage('token')
  if (token) {
    config.header['token'] = token
  }
  return config
}
// 响应拦截器
instance.interceptors.response = async (response) => {
  const { isSuccess, data } = response
  if (!isSuccess) {
    wx.toast({
      title: '网络异常，请重试！',
      icon: 'error'
    })
    return Promise.reject(response)
  }
  switch (data.code) {
    case 200:
      return data
    case 208:
      const res = await wx.modal({
        content: '请重新登录！！！',
        showCancel: false
      })
      if (res) {
        clearStorage()
        wx.navigateTo({
          url: '/pages/login/login'
        })
      }
      return Promise.reject(response)

    default:
      wx.toast({
        title: '程序出现错误，请重试！'
      })
      return Promise.reject(response)
  }
}

export default instance
